<template>
  <div class="app-content-wrap" :style="'minHeight:' + gHeight + 'px;'">
    <div class="g-content-title">{{ pageTitle }}</div>

    <el-form :model="userObj" :rules="rules" ref="userModifyForm" label-width="80px" size="small" style="width:90%">
      <el-form-item label="用户姓名" prop="userName">
        <el-input v-model="userObj.userName" placeholder="用户姓名"></el-input>
      </el-form-item>
      <!-- <el-form-item label="用户编号" prop="userId">
        <el-input v-model="userObj.userId" placeholder="用户编号" :readonly="ifReadonly"></el-input>
      </el-form-item> -->
      <el-form-item label="用户性别">
        <el-select v-model="userObj.gender" placeholder="选择性别">
          <el-option v-for="item in subTypeArr" :key="item.value" :value="item.value" :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input v-model="userObj.mobile" maxlength="11" placeholder="手机号码"></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="cardNo">
        <el-input v-model="userObj.cardNo" placeholder="身份证号"></el-input>
      </el-form-item>
      <el-row :gutter="15">
        <el-col v-if="this.$route.params.userId === 'addUser'">
          <el-form-item label="所属小区" prop="deptId">
            <SelectArea class="select__area" :selectModel="userObj.deptId" :areaIds="areaIds" :multiple="true" @onAreaChange="onAreaChange" hideThird="true"></SelectArea>
          </el-form-item>
        </el-col>
        <el-col v-else>
          <el-form-item label="所属小区" prop="deptId">
            <el-select v-model="userObj.deptId" filterable multiple placeholder="请选择">
              <el-option v-for="item in areaArr" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item style="padding-left:7px;">
        <el-button type="primary" size="small" @click="modifyUser()">提 交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import SelectArea from '../../components/common/select/areaMultiple.vue'
import { validPhone, checkCardNumber } from '../../assets/scripts/base/validate.js'

let rulePhone = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    if (!validPhone(value)) {
      callback(new Error('请输入正确的手机号码！'))
    } else {
      callback()
    }
  }
}

let validCardNumber = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    if (!checkCardNumber(value)) {
      callback(new Error('请输入正确的身份证号码！'))
    } else {
      callback()
    }
  }
}

export default {
  name: 'userModify',
  components: {
    SelectArea
  },
  data () {
    return {
      gHeight: this.$store.state.gHeight,
      ifReadonly: true, // 用户名是否readOnly
      subTypeArr: [],
      moduleArray: [],
      userObj: {
        userId: '',
        deptId: [],
        mobile: '',
        userName: '',
        cardNo: '',
        password: '',
        userPhone: '',
        jobNbr: '',
        gender: null
      },
      areaIds: {
        areaId1: '',
        areaId2: []
      },
      areaArr: [],
      rules: {
        // userId: [
        //   { required: true, message: '用户编号不能为空', trigger: 'blur' }
        // ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: rulePhone, trigger: 'blur' }
        ],
        cardNo: [
          { required: true, message: '请输入正确的身份证号', trigger: 'blur' },
          { validator: validCardNumber, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '所属小区不能为空', trigger: ['blur'] }
        ]
      },
      pageTitle: '',
      showSelectDept: false // 显示隐藏所属下拉菜单
      // tempRoleName: '' // 缓存角色名
    }
  },
  methods: {
    // 提交修改用户
    modifyUser () {
      if (this.$route.params.userId === 'addUser') {
        this.insertUser()
      } else {
        let data = {
          userId: this.userObj.userId,
          userName: this.userObj.userName,
          mobile: this.userObj.mobile,
          gender: this.userObj.gender,
          cardNo: this.userObj.cardNo,
          deptIds: this.userObj.deptId
        }
        let url = this.$base.getUrl('appletUpdateManager')

        this.$refs['userModifyForm'].validate((valid) => {
          if (valid) {
            this.$store.dispatch('postForm', {
              isJson: true,
              url: url,
              data: data
            }).then(res => {
              if (res.code === 0) {
                this.$message({
                  type: 'success',
                  message: '修改成功！'
                })
                this.$router.push({
                  name: 'appletManager'
                })
              } else {
                this.$message.error('抱歉修改失败！')
              }
            })
          } else {
            return false
          }
        })
      }
    },
    // 新增管理员
    insertUser () {
      let url = this.$base.getUrl('appletAddManager')

      this.$refs['userModifyForm'].validate((valid) => {
        if (valid) {
          this.$store.dispatch('postForm', {
            isJson: true,
            url: url,
            data: {
              // userId: this.userObj.userId,
              userName: this.userObj.userName,
              mobile: this.userObj.mobile,
              gender: this.userObj.gender,
              cardNo: this.userObj.cardNo,
              deptIds: this.userObj.deptId
            }
          }).then(res => {
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '添加成功！'
              })
              this.$router.push({
                name: 'appletManager'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 初始获取用户信息
    getUser () {
      let url = this.$base.getUrl('appletManagerInfo')
      this.$store.dispatch('postForm', {
        isJson: true,
        url: url,
        data: {
          userId: this.$route.params.userId
        }
      }).then(res => {
        let { result } = res
        if (result) {
          // this.userObj.userId = result.userId
          let deptTree = result.deptTree.nodes
          if (deptTree && deptTree.length) {
            for (let i of deptTree) {
              this.areaIds.areaId1 = i.deptId
              if (i.nodes && i.nodes.length) {
                for (let j of i.nodes) {
                  this.userObj.deptId.push(j.deptId)
                  this.areaIds.areaId2.push(j.deptId)
                }
              }
            }
          }

          this.userObj.userId = result.userId
          this.userObj.mobile = result.mobile
          this.userObj.userName = result.userName
          this.userObj.gender = parseInt(result.gender)
          this.userObj.cardNo = result.cardNo
          this.userObj.userPhone = result.userPhone
        } else {
          this.$message.error('拉取用户信息失败')
        }
      })
    },
    // 初始获取所有小区
    getAllDeptment () {
      let url = this.$base.getUrl('getTree')
      let params = {
        url: url,
        data: {}
      }
      this.$store.dispatch('getForm', params).then(res => {
        this.areaArr = res.nodes
        if (res.nodes && res.nodes.length) {
          for (let i of res.nodes) {
            if (i.nodes && i.nodes.length) {
              for (let j of i.nodes) {
                this.areaArr.push({
                  label: j.deptName,
                  value: j.deptId
                })
              }
            }
          }
        }
      })
    },
    // area组件change时
    onAreaChange (val) {
      this.userObj.deptId = val
    }
  },
  mounted () {
    this.subTypeArr = this.$base.getConst('select', 'userGender')
    if (this.$route.params.userId === 'addUser') {
      this.ifReadonly = false
      this.pageTitle = '管理员新增'
    } else {
      this.getAllDeptment()
      this.getUser()
      this.pageTitle = '管理员编辑'
    }
  }
}
</script>

<style scoped>
.select__area /deep/ .select__street {
  padding: 0 !important;
}
.select__area /deep/ .select__community {
  padding-right: 0 !important;
}
.select__area /deep/ .select__department {
  padding-right: 0 !important;
}
</style>
